
package com.xksoft.xutao.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class XuTao implements EntryPoint, ClickListener
{

	private VerticalPanel vp = null;

	private Button btnStart = null;

	private Button btnStop = null;

	private HTML content = null;

	private Timer timer = null;

	private Button btnAgain = null;

	private List<Integer> selected = new ArrayList<Integer>();
	
	private int currentNum;

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad()
	{
		initPage();
		timer = new Timer()
		{
			public void run()
			{
				int n = getNext();
				content.setHTML(String.valueOf(n));
			}

		};
		// timer.scheduleRepeating(20);
		RootPanel superRoot = RootPanel.get();
		superRoot.addStyleName("background-color");
		RootPanel root = RootPanel.get("main_frame");
		// root.addStyleName("background-color");
		root.add(vp);
	}

	private void initPage()
	{

		String str = "囍";

		content = new HTML(str);
		content.addStyleName("number-size");
		btnStart = new Button("Push Me");
		btnStart.addClickListener(this);
		btnStop = new Button("Lucky  Me");
		btnStop.addClickListener(this);
		btnAgain = new Button("Try Again");
		btnAgain.addClickListener(this);
		vp = new VerticalPanel();
		vp.add(content);
		vp.add(btnStart);
		vp.setCellHorizontalAlignment(btnStart, HasHorizontalAlignment.ALIGN_CENTER);
	}

	private int getNext()
	{
		int num = Random.nextInt(100);
		while (isSelected(num))
		{
			num = Random.nextInt(100);
		}

		currentNum = num;
		return num + 1;
	}

	private boolean isSelected(int i)
	{
		for (Integer o : selected)
		{
			int num = o;
			if (i == num)
				return true;
		}
		return false;
	}

	public void onClick(Widget sender)
	{
		if (sender == btnStart)
		{
			timer.scheduleRepeating(20);
			vp.remove(btnStart);
			vp.add(btnStop);
			vp.setCellHorizontalAlignment(btnStop, HasHorizontalAlignment.ALIGN_CENTER);
		}
		if (sender == btnStop)
		{
			timer.cancel();
			vp.remove(btnStop);
			vp.add(btnAgain);
			selected.add(currentNum);
			vp.setCellHorizontalAlignment(btnAgain, HasHorizontalAlignment.ALIGN_CENTER);
		}
		if (sender == btnAgain)
		{
//			timer.run();
			vp.remove(btnAgain);
			vp.add(btnStop);
			timer.scheduleRepeating(20);
			vp.setCellHorizontalAlignment(btnStop, HasHorizontalAlignment.ALIGN_CENTER);
		}
	}
}
